/*
 * 登录用户
 *
 * @Author:
 * @Date: 
 * @Wechat: 
 * @Email: 
 * @Copyright 
 */
import _ from 'lodash';
import { defineStore } from 'pinia';
import { HOME_PAGE_NAME } from '../../../constants/home-const';
import { MENU_TYPE_ENUM } from '../../../constants/menu-const';
import { MessageAPI } from "/@/api/xstage/message";
import { lxSentry } from '/@/lib/lx-sentry.js';
import { localRead, localSave, localRemove } from '/@/lib/localstorage';
import { setToken, getToken, removeToken, getAppInfo, setAppInfo, setMenuList, getMenuList, removeMessage, getMenuOperations, getMessage, removeMenuOperations, removeAppConfig } from "/@/utils/storage";
import { buildMenuTree, buildMenuParentIdListMap } from "/@/utils/menu";
import { router } from '/@/router';
import { MenuAPI } from '/@/api/xstage/menu';

export const useUserStore = defineStore({
  id: 'userStore',
  state: () => ({
    token: getToken(),
    //员工id
    employeeId: '',
    // 头像
    avatar: '',
    //登录名
    loginName: '',
    //姓名
    actualName: '',
    //手机号
    phone: '',
    //部门id
    departmentId: '',
    //部门名词
    departmentName: '',
    //是否需要修改密码
    needUpdatePwdFlag: false,
    //是否为超级管理员
    administratorFlag: true,
    //上次登录ip
    lastLoginIp: '',
    //上次登录ip地区
    lastLoginIpRegion: '',
    //上次登录 设备
    lastLoginUserAgent: '',
    //上次登录时间
    lastLoginTime: '',
    //左侧菜单树形结构
    menuTree: [],
    //存在页面路由的菜单集合
    menuRouterList: [],
    //是否完成menuRouter初始化
    menuRouterInitFlag: false,
    //父类菜单集合
    menuParentIdListMap: new Map(),
    // 功能点集合
    pointsList: [],
    // 标签页
    tagNav: null,
    // 缓存
    keepAliveIncludes: [],
    // 未读消息数量
    unreadMessageCount: 0,
    // 待办工作数
    toBeDoneCount: 0,

    // 用户信息
    userInfo: {},
    // app信息
    appInfo: getAppInfo()
  }),
  getters: {
    getToken(state) {
      if (state.token) {
        return state.token;
      }
      return getToken();
    },
    getAppInfo(state) {
      if (state.appInfo) {
        return state.appInfo;
      }
      return getAppInfo();
    },
    getNeedUpdatePwdFlag(state) {
      return state.needUpdatePwdFlag;
    },
    //是否初始化了 路由
    getMenuRouterInitFlag(state) {
      return state.menuRouterInitFlag;
    },
    //菜单树
    getMenuTree(state) {
      if (state.menuTree.length > 0) {
        return state.menuTree;
      }
      return getMenuList();
    },
    //菜单的路由
    getMenuRouterList(state) {
      return state.menuRouterList;
    },
    //菜单的父级id
    getMenuParentIdListMap(state) {
      return state.menuParentIdListMap;
    },
    //功能点（菜单权限）
    getPointList(state) {
      if (_.isEmpty(state.pointsList)) {
        let localUserPoints = getMenuOperations() || '';
        state.pointsList = localUserPoints ? JSON.parse(localUserPoints) : [];
      }
      return state.pointsList;
    },
    //标签页
    getTagNav(state) {
      if (_.isNull(state.tagNav)) {
        state.tagNav = [];
      }
      let tagNavList = _.cloneDeep(state.tagNav) || [];
      tagNavList.unshift({
        menuName: HOME_PAGE_NAME,
        menuTitle: '首页',
      });
      return tagNavList;
    },
  },

  actions: {
    async logout() {
      try {
        // 调用退出接口
        // await loginApi.logout();
      } catch (e) {
        lxSentry.captureError(e);
      } finally {
        this.token = '';
        this.menuList = [];
        this.tagNav = [];
        this.unreadMessageCount = 0;
        removeToken();
        removeMenuOperations();
        removeAppConfig();
        removeMessage();
        // router.replace('/login');
      }
    },
    // 查询未读消息数量
    async queryUnreadMessageCount() {
      try {
        let result = await MessageAPI.queryUnreadCount();
        this.unreadMessageCount = result.data;
      } catch (e) {
        lxSentry.captureError(e);
      }
    },
    async queryToBeDoneList() {
      try {
        let localToBeDoneList = getMessage();
        if (localToBeDoneList) {
          this.toBeDoneCount = JSON.parse(localToBeDoneList).filter((e) => !e.doneFlag).length;
        }
      } catch (err) {
        lxSentry.captureError(err);
      }
    },
    // 设置token
    setToken(token) {
      this.token = token;
      setToken(token);
    },
    //设置登录信息
    async setUserLoginInfo(data) {
      // 用户基本信息
      this.userInfo = data.user;
      this.appInfo = data.app;
      setAppInfo(data.app || "")

      const { list, childMenuList, boardMenuList, allMenu } = await this.getMenuList({ oauth: data.token });

      //菜单权限
      this.menuTree = buildMenuTree(list);
      setMenuList(this.menuTree);

      console.log(this.menuTree, "this.menuTree");


      //拥有路由的菜单
      this.menuRouterList = allMenu.filter((e) => e.url);

      console.log(this.menuRouterList);

      //父级菜单集合
      this.menuParentIdListMap = buildMenuParentIdListMap(this.menuTree);
      // //功能点
      // this.pointsList = data.menuList.filter((menu) => menu.menuType === MENU_TYPE_ENUM.POINTS.value && menu.visibleFlag && !menu.disabledFlag);

      // // 获取用户未读消息
      // this.queryUnreadMessageCount();
      // // 获取待办工作数
      // this.queryToBeDoneList();
    },
    //设置当前登录账号信息
    async setUserInfo(data) {
      this.userInfo = data.user;
    },

    //设置标签页
    setTagNav(route, from) {
      if (_.isNull(this.tagNav)) {
        this.tagNav = [];
      }
      // name唯一标识
      let name = route.name;
      if (!name || name === HOME_PAGE_NAME || name === '403' || name === '404') {
        return;
      }
      let findTag = (this.tagNav || []).find((e) => e.menuName === name);
      if (findTag) {
        // @ts-ignore
        findTag.fromMenuName = from.name;
        findTag.fromMenuQuery = from.query;
      } else {
        // @ts-ignore
        this.tagNav.push({
          // @ts-ignore
          menuName: name,
          // @ts-ignore
          menuTitle: route.meta.title,
          menuQuery: route.query,
          menuIcon: route.meta?.icon,
          // @ts-ignore
          fromMenuName: from.name,
          fromMenuQuery: from.query,
        });
      }
    },
    //关闭标签页
    closeTagNav(menuName, closeAll) {
      if (_.isEmpty(this.getTagNav)) return;
      if (closeAll && !menuName) {
        this.tagNav = [];
        this.clearKeepAliveIncludes();
      } else {
        let findIndex = (this.tagNav || []).findIndex((e) => e.menuName === menuName);
        if (closeAll) {
          if (findIndex === -1) {
            this.tagNav = [];
            this.clearKeepAliveIncludes();
          } else {
            let tagNavElement = (this.tagNav || [])[findIndex];
            this.tagNav = [tagNavElement];
            this.clearKeepAliveIncludes(tagNavElement.menuName);
          }
        } else {
          (this.tagNav || []).splice(findIndex, 1);
          this.deleteKeepAliveIncludes(menuName);
        }
      }
    },
    //关闭页面
    closePage(route, router, path) {
      if (!this.getTagNav || _.isEmpty(this.getTagNav)) return;
      if (path) {
        router.push({ path });
      } else {
        // 寻找tagNav
        let index = this.getTagNav.findIndex((e) => e.menuName === route.name);
        if (index === -1) {
          router.push({ name: HOME_PAGE_NAME });
        } else {
          let tagNav = this.getTagNav[index];
          if (tagNav.fromMenuName && this.getTagNav.some((e) => e.menuName === tagNav.fromMenuName)) {
            router.push({ name: tagNav.fromMenuName, query: tagNav.fromMenuQuery });
          } else {
            // 查询左侧tag
            let leftTagNav = this.getTagNav[index - 1];
            router.push({ name: leftTagNav.menuName, query: leftTagNav.menuQuery });
          }
        }
      }
      this.closeTagNav(route.name, false);
    },
    // 加入缓存
    pushKeepAliveIncludes(val) {
      if (!val) {
        return;
      }
      if (!this.keepAliveIncludes) {
        this.keepAliveIncludes = [];
      }
      if (this.keepAliveIncludes.length < 30) {
        let number = this.keepAliveIncludes.findIndex((e) => e === val);
        if (number === -1) {
          this.keepAliveIncludes.push(val);
        }
      }
    },
    // 删除缓存
    deleteKeepAliveIncludes(val) {
      if (!this.keepAliveIncludes || !val) {
        return;
      }
      let number = this.keepAliveIncludes.findIndex((e) => e === val);
      if (number !== -1) {
        this.keepAliveIncludes.splice(number, 1);
      }
    },
    // 清空缓存
    clearKeepAliveIncludes(val) {
      if (!val || !this.keepAliveIncludes.includes(val)) {
        this.keepAliveIncludes = [];
        return;
      }
      this.keepAliveIncludes = [val];
    },

    /**
    * 获取菜单权限
    * @param commit
    * @param state
    * @returns {Promise<unknown>}
    */
    getMenuList() {
      return new Promise((resolve) => {
        console.log("getMenuList")
        if (window.TEST_MODE) {
          resolve({ list: [], childMenuList: [] });
        } else {
          // 根据token获取菜单
          MenuAPI.listMenuByUserId().then(({ list, childMenuList, boardMenuList, allMenu }) => {
            resolve({ list, childMenuList, boardMenuList, allMenu });
          });
        }
      });
    },
  },
});